<template>
  <view class="lt-container">
    
    <view class="bg-layer">
      <view class="bg-grid"></view>
      <text class="bg-text">ARCHIVES</text>
    </view>

    <view class="header-section">
      <view class="page-title">
        <text class="title-main">RESUME DATABASE</text>
        <text class="title-sub">人员档案库 // 管理终端</text>
      </view>
      
      <view class="action-bar">
        <button class="btn-primary" hover-class="btn-hover" @click="handleUpload">
          <text class="btn-icon">+</text>
		    <text class="btn-icon">UPLOAD NEW FILE</text>
        </button>
      </view>
    </view>

    <scroll-view scroll-y class="list-viewport">
      <view class="list-content">
        <view v-if="listData.length === 0" class="empty-state">
          <text class="empty-text">NO DATA FOUND</text>
        </view>

        <view 
          class="resume-card" 
          v-for="(item, index) in listData" 
          :key="index"
        >
          <view class="card-deco-line"></view>
          
          <view class="card-main">
            <view class="file-icon-box">
              <text class="file-type">DOC</text>
            </view>
            
            <view class="file-info">
              <text class="file-title">{{ item.title }}</text>
              <text class="file-meta">TARGET: {{ item.targetJobTitle }}</text>
              <text class="file-meta">ID: {{ item.id || '000' + index }}</text>
            </view>
          </view>

          <view class="card-actions">
            <view class="action-btn ai-btn" @click="handleAI(item)">
              <text>AI OPTIMIZE</text>
            </view>
            <view class="action-group-right">
              <view class="icon-btn" @click="handleEdit(item)">EDIT</view>
              <view class="icon-btn delete" @click="handleDelete(item)">DEL</view>
            </view>
          </view>
        </view>
      </view>
      
      <view style="height: 40rpx;"></view>
    </scroll-view>

    <view class="modal-mask" v-if="showModal" @touchmove.stop.prevent>
      <view class="lt-modal">
        <view class="modal-header">
          <text class="modal-title">UPLOAD PROTOCOL</text>
          <text class="modal-close" @click="closeModal">×</text>
        </view>
        
        <view class="modal-body">
          <view class="input-group">
            <text class="input-label">FILE TITLE // 简历标题</text>
            <input class="lt-input" type="text" placeholder="INPUT TITLE" placeholder-class="ph-style" v-model="formData.title" />
          </view>

          <view class="input-group">
            <text class="input-label">TARGET POSITION // 目标岗位</text>
            <input class="lt-input" type="text" placeholder="INPUT POSITION" placeholder-class="ph-style" v-model="formData.targetJob" />
          </view>

          <view class="file-select-area">
            <text class="input-label">ATTACHMENT // 附件</text>
            
            <view class="file-box" v-if="!formData.fileName" @click="chooseFile">
              <text class="plus-icon">+</text>
              <text class="select-text">SELECT DOCUMENT</text>
              <text class="file-limit">PDF / DOC / DOCX</text>
            </view>

            <view class="file-box active" v-else>
              <view class="file-preview">
                <text class="file-icon">📄</text>
                <text class="selected-name">{{ formData.fileName }}</text>
              </view>
              <text class="re-select" @click="chooseFile">CHANGE</text>
            </view>
          </view>
        </view>

        <view class="modal-footer">
          <button class="lt-btn cancel" hover-class="btn-hover" @click="closeModal">CANCEL</button>
          <button class="lt-btn confirm" hover-class="btn-hover" @click="submitUpload">
            {{ isUploading ? 'UPLOADING...' : 'CONFIRM UPLOAD' }}
          </button>
        </view>
      </view>
    </view>

  </view>
</template>

<script>

import { selectResumesByUserid,deleteByResumeid } from '../../api/resume/resume';
import { selectResumesReportByresumeid,Resumesscore } from '../../api/resume/ResumeReport';


export default {
  data() {
    return {
      // 列表数据
      listData: [],
      
      // 弹窗控制
      showModal: false,
      isUploading: false,
      
      // 表单数据
      formData: {
        title: '',
        targetJob: '',
        fileName: '',
        filePath: ''
      }
    }
  },
  onLoad() {
    this.getResumes();
  },
  methods: {
    // 获取简历列表
    getResumes() {
      uni.showLoading({ title: 'SYNCING...' });
      selectResumesByUserid().then(res => {
        uni.hideLoading();
        if(res.code === 200) {
          this.listData = res.data;
        }
      }).catch(() => {
        uni.hideLoading();
        // 模拟数据用于展示效果 (如果接口失败)
        /*
        this.listData = [
          { id: 1, title: '高级前端开发简历', targetJobTitle: 'Senior Frontend Dev' },
          { id: 2, title: 'Java工程师求职', targetJobTitle: 'Backend Engineer' }
        ];
        */
      });
    },

    // 打开上传弹窗
    handleUpload() {
      this.formData = { title: '', targetJob: '', fileName: '', filePath: '' };
      this.showModal = true;
    },

    // 关闭弹窗
    closeModal() {
      if(this.isUploading) return;
      this.showModal = false;
    },

    // 选择文件
    chooseFile() {
      // #ifdef MP-WEIXIN
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['pdf', 'doc', 'docx'],
        success: (res) => {
          const file = res.tempFiles[0];
          this.formData.fileName = file.name;
          this.formData.filePath = file.path;
        }
      });
      // #endif

      // #ifdef H5
      uni.chooseFile({
        count: 1,
        extension: ['.pdf', '.doc', '.docx'],
        success: (res) => {
          const file = res.tempFilePaths[0]; // H5 返回格式可能不同，需根据实际调整
          const fileObj = res.tempFiles[0];
          this.formData.fileName = fileObj.name;
          this.formData.filePath = fileObj.path || fileObj; // H5可能直接是Blob对象
        }
      });
      // #endif
    },

    // 提交上传
    submitUpload() {
      const { title, targetJob, filePath } = this.formData;
      if (!title || !targetJob || !filePath) {
        uni.showToast({ title: 'DATA INCOMPLETE', icon: 'none' });
        return;
      }

      this.isUploading = true;
      
      uni.uploadFile({
        url: 'http://localhost:8080/interview/resumes/uploadResumes', // 你的接口
        filePath: filePath,
        name: 'file',
        formData: {
          'title': title,
          'targetJobTitle': targetJob
        },
        // header: { "Authorization": ... },
        success: (res) => {
          this.isUploading = false;
          let data = JSON.parse(res.data);
          if (data.code === 200) {
            uni.showToast({ title: 'UPLOAD SUCCESS' });
            this.closeModal();
            this.getResumes(); // 刷新列表
          } else {
            uni.showToast({ title: 'UPLOAD FAILED', icon: 'none' });
          }
        },
        fail: () => {
          this.isUploading = false;
          uni.showToast({ title: 'NETWORK ERROR', icon: 'none' });
        }
      });
    },
	
	
	LodingReportAndtoReport(item)
	{
		selectResumesReportByresumeid(item.resumeId).then(res=>{
		
			if(res.code==200)
			{
				uni.navigateTo({
				url:'/pages/resume/ResumeReport/ResumeReport?resumeId='+item.resumeId
				})
			}else{
				uni.showModal({
						title: 'CONFIRMATION // 操作确认', // 使用全大写英文+中文的机械风格
						content: '检测到未生成的评估报告。\n是否立即执行生成协议？\n\nInitiate generation protocol?', // 双语+换行
						confirmText: 'EXECUTE', // 硬核指令感
						cancelText: 'ABORT',    // 放弃指令
						confirmColor: '#79BBA9', // 孤星青
						cancelColor: '#888888',  // 工业灰
				      success: (res) => {
				        if (res.confirm) {
				          // --- 重点在这里 ---
				          // 用户点击了“确定”，调用你真正想执行的方法
						  Resumesscore(item).then(res=>{
						  		uni.navigateTo({
						  			url:'/pages/resume/ResumeReport/ResumeReport?resumeId='+item.resumeId
						  			})
						  	
						  })
				        
				        } else if (res.cancel) {
				          console.log('用户点击了取消，什么都不做');
				        }
				      }
				    });
				
			
			}
		})
		
	},

    // 功能按钮
    handleAI(item) {
	
		this.LodingReportAndtoReport(item);
		
		
		
		
      uni.showToast({ title: `OPTIMIZING: ${item.title}`, icon: 'none' });
    },
    handleEdit(item) {
		uni.navigateTo({
			
			url:'/pages/resume/edit/edit',
			success: function(res) {
			        res.eventChannel.emit('sendJsonData', { 
			            resumeData: item
			        });
			    }
		})
      console.log('Edit', item);
    },
    handleDelete(item) {
      uni.showModal({
        title: 'WARNING',
        content: 'Confirm deletion? This action cannot be undone.',
        confirmColor: '#9A332D',
        success: (res) => {
          if (res.confirm) {
			  deleteByResumeid(item.resumeId).then(res=>{
				  if (res.code === 200) {
				                      // ** 建议补充点 **
				                      
				                      // 1. 成功提示
				                      wx.showToast({
				                          title: '删除成功',
				                          icon: 'success',
				                          duration: 1500
				                      });
				  
				                      // 2. 刷新页面数据（最关键的一步）
				                      // 假设您的列表数据加载函数叫做 getResumeList
				                      this.getResumes(); 
				                      
				                  } else {
				                      // 后端业务逻辑失败（如：未找到记录）
				                      wx.showModal({
				                          title: '删除失败',
				                          content: res.msg || '操作失败，请重试',
				                          showCancel: false
				                      });
				                  }
				  
			  })
			  
            console.log('Deleted', item.resumeId);
            // 调用删除接口...
          }
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
/* === 孤星风格变量 === */
$lt-bg: #E0E2E5;
$lt-card: rgba(255, 255, 255, 0.92);
$lt-text: #1a1a1a;
$lt-sub: #666;
$c-green: #79BBA9;
$c-yellow: #E6A73C;
$c-red: #9A332D;

.lt-container {
  min-height: 100vh;
  background-color: $lt-bg;
  color: $lt-text;
  font-family: Helvetica, sans-serif;
  position: relative;
}

/* 背景 */
.bg-layer {
  position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 0;
  pointer-events: none; overflow: hidden;
}
.bg-grid {
  width: 100%; height: 100%;
  background-image: linear-gradient(rgba(0,0,0,0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(0,0,0,0.03) 1px, transparent 1px);
  background-size: 40rpx 40rpx;
}
.bg-text {
  position: absolute; top: 100rpx; right: -40rpx;
  font-size: 160rpx; font-weight: 900; color: rgba(0,0,0,0.03);
  transform: rotate(90deg);
}

/* 顶部操作栏 */
.header-section {
  position: relative; z-index: 10;
  padding: 40rpx 30rpx;
  background: rgba(255,255,255,0.6);
  backdrop-filter: blur(5px);
  border-bottom: 2rpx solid rgba(0,0,0,0.05);
  display: flex; justify-content: space-between; align-items: center;
}
.page-title { display: flex; flex-direction: column; }
.title-main { font-size: 40rpx; font-weight: 900; letter-spacing: 2rpx; line-height: 1; }
.title-sub { font-size: 20rpx; color: $lt-sub; margin-top: 8rpx; letter-spacing: 2rpx; }

/* 主上传按钮 */
.btn-primary {
  background: $lt-text; color: #fff;
  font-size: 24rpx; font-weight: bold;
  padding: 0 30rpx; height: 70rpx; line-height: 70rpx;
  border-radius: 0;
  clip-path: polygon(10rpx 0, 100% 0, 100% calc(100% - 10rpx), calc(100% - 10rpx) 100%, 0 100%, 0 10rpx);
  display: flex; align-items: center;
}
.btn-icon { margin-right: 10rpx; font-size: 30rpx; }
.btn-hover { opacity: 0.8; transform: scale(0.98); }

/* 列表区域 */
.list-viewport {
  height: calc(100vh - 160rpx); /* 减去头部高度 */
  box-sizing: border-box;
}
.list-content { padding: 30rpx; }

/* 空状态 */
.empty-state {
  text-align: center; margin-top: 200rpx;
  color: $lt-sub; font-family: monospace; letter-spacing: 4rpx;
  opacity: 0.5;
}

/* 简历卡片 */
.resume-card {
  background: $lt-card;
  margin-bottom: 30rpx;
  padding: 30rpx;
  position: relative;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 20rpx), calc(100% - 20rpx) 100%, 0 100%);
}
.card-deco-line {
  position: absolute; top: 0; left: 0; width: 8rpx; height: 100%;
  background: $c-green;
}

.card-main {
  display: flex; align-items: flex-start; margin-bottom: 20rpx;
}
.file-icon-box {
  width: 80rpx; height: 80rpx;
  background: rgba(0,0,0,0.05);
  display: flex; align-items: center; justify-content: center;
  margin-right: 24rpx; border: 1px solid rgba(0,0,0,0.1);
}
.file-type { font-size: 20rpx; font-weight: 900; color: $lt-text; }

.file-info { flex: 1; display: flex; flex-direction: column; }
.file-title { font-size: 30rpx; font-weight: bold; color: $lt-text; margin-bottom: 6rpx; }
.file-meta { font-size: 22rpx; color: $lt-sub; font-family: monospace; }

/* 卡片操作栏 */
.card-actions {
  display: flex; justify-content: space-between; align-items: center;
  border-top: 1px dashed rgba(0,0,0,0.1);
  padding-top: 20rpx;
}
.ai-btn {
  background: rgba($c-yellow, 0.1); color: darken($c-yellow, 10%);
  font-size: 22rpx; font-weight: bold;
  padding: 10rpx 20rpx; border-radius: 4rpx;
}
.action-group-right { display: flex; gap: 30rpx; }
.icon-btn {
  font-size: 22rpx; font-weight: bold; color: $lt-sub;
  border-bottom: 2rpx solid transparent;
}
.icon-btn.delete { color: $c-red; }

/* === 弹窗样式 (孤星风格) === */
.modal-mask {
  position: fixed; top: 0; left: 0; width: 100%; height: 100%;
  background: rgba(0,0,0,0.6); backdrop-filter: blur(5px);
  z-index: 999; display: flex; justify-content: center; align-items: center;
}
.lt-modal {
  width: 600rpx;
  background: #fff;
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 30rpx), calc(100% - 30rpx) 100%, 0 100%);
}
.modal-header {
  padding: 30rpx; border-bottom: 2rpx solid #eee;
  display: flex; justify-content: space-between; align-items: center;
}
.modal-title { font-size: 28rpx; font-weight: 900; letter-spacing: 2rpx; }
.modal-close { font-size: 40rpx; color: $lt-sub; line-height: 1; }

.modal-body { padding: 40rpx 30rpx; }
.input-group { margin-bottom: 30rpx; }
.input-label { display: block; font-size: 20rpx; color: $lt-sub; font-weight: bold; margin-bottom: 10rpx; }
.lt-input {
  background: rgba(0,0,0,0.03); height: 70rpx; padding: 0 20rpx;
  font-size: 26rpx; color: $lt-text; border-bottom: 2rpx solid #ddd;
}
.ph-style { color: #ccc; }

.file-select-area { margin-top: 20rpx; }
.file-box {
  border: 2rpx dashed #ccc; padding: 30rpx;
  display: flex; flex-direction: column; align-items: center; justify-content: center;
  background: #fafafa;
}
.file-box.active { border-color: $c-green; background: rgba($c-green, 0.05); }
.plus-icon { font-size: 50rpx; color: $lt-sub; margin-bottom: 10rpx; }
.select-text { font-size: 24rpx; font-weight: bold; color: $lt-text; }
.file-limit { font-size: 20rpx; color: #999; margin-top: 6rpx; }

.file-preview { display: flex; align-items: center; margin-bottom: 10rpx; }
.selected-name { font-size: 24rpx; color: $lt-text; margin-left: 10rpx; max-width: 400rpx; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.re-select { font-size: 20rpx; color: $c-green; font-weight: bold; text-decoration: underline; }

.modal-footer {
  padding: 30rpx; display: flex; gap: 20rpx;
}
.lt-btn {
  flex: 1; height: 80rpx; line-height: 80rpx;
  border-radius: 0; font-size: 24rpx; font-weight: bold;
}
.lt-btn::after { border: none; }
.cancel { background: #eee; color: #666; }
.confirm { background: $lt-text; color: #fff; }

</style>